#!/bin/bash

workingDir=$PWD
dumpDir="./data/sql/"
db="SugarBindDB"
schema="public"

file_name="SugarBindDB_140522_000005.sql"


#procpid for 9.1, pid for 9.2
killQuery_91=" SELECT pg_terminate_backend(pg_stat_activity.procpid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '$db'"
killQuery_92=" SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '$db'"

cd $workingDir
echo "cd $workingDir"

cd $dumpDir
echo "cd $dumpDir"

#kill all connections
#psql -d $db -c "$killQuery_91"
#echo "$killQuery_91"
#psql -d $db -c "$killQuery_92"
#echo "$killQuery_92"

#dropdb $db
#echo "$db dropped"

#createdb $db
#echo "$db created"

#drop schema#
dropSchemaQuery=" DROP SCHEMA IF EXISTS $schema CASCADE;"
createSchemaQuery=" CREATE SCHEMA public;"

echo "$dropSchemaQuery"
psql -d $db -c "$dropSchemaQuery"
echo "$createSchemaQuery"
psql -d $db -c "$createSchemaQuery"

psql -d $db < $file_name
echo "file $file_name dumped in $db database."

echo "Re-connection to $db database."
psql $db << EOF

EOF
